<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="大模型类型" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请选择大模型类型"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型ID" prop="appId" label-width="80px">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入模型ID"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型名称" prop="scene" label-width="80px">
        <el-input
          v-model="queryParams.scene"
          placeholder="请输入模型名称"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:param:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:param:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:param:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelConfigList">
      <el-table-column label="大模型类型" align="center" prop="modelType" :formatter="this.modelNameFormat"/>
      <el-table-column label="模型名称" align="center" prop="name" />
      <el-table-column label="接口信息" align="center" prop="modelParam" width="300" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <i class="el-icon-document-copy" v-clipboard:copy="scope.row.modelParam" v-clipboard:success="copyText" style="margin-right: 5px;cursor: pointer;"></i>
          {{ scope.row.modelParam }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            v-hasPermi="['model:param:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:param:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:param:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              @click="updateStatus(scope.row)"
              v-hasPermi="['model:param:query']"
          >
            <span v-show="scope.row.status == 1">停用</span>
            <span v-if="scope.row.status == 0">启用</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改大模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <!--详情-->
      <div v-show="!isEdit" style="margin-left: 15px">
        <el-row>
          <el-col :span="2">
            <div style="margin-left:10px;height: 80px;width: 80px;">
              <div>
                <el-image
                  style="width: 76px; height: 76px"
                  :src="form.logoUrl"
                  :fit="fill">
                </el-image>
              </div>
            </div>
          </el-col>
          <el-col span="15">
            <div style="margin-left: 10px">
              <div>
            <span style="font-size: 18px;font-weight: bold;color: #495060">
              {{form.name}}
            </span>
                <span v-show="form.status == 1" style="margin-left: 10px">
              <el-tag type="success" size="small">正常</el-tag>
            </span>
                <span v-show="form.status == 0" style="margin-top: 5px">
              <el-tag type="info" size="small">停用</el-tag>
            </span>
              </div>
              <div>
            <span>
              <span style="color: #515a6e">模型类型：</span>
              <span>{{this.form.modelName}}</span>
            </span>
                <span>
              <span style="color: #515a6e;margin-left: 60px">模型编号：</span>
              <span>{{this.form.uid}}</span>
            </span>
              </div>
              <div>
                <span style="color: #515a6e">接口信息：</span>
                <span>{{this.form.formatModelParam}}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="7">
            <el-button type="primary"
                       @click="handlerEdit"
                       size="small">
              <span>编辑</span>
            </el-button>
            <el-button type="danger"
                       plain
                       size="small"
                       @click="handlerDeleteEdit">
              <span>删除</span>
            </el-button>
            <el-button type="info"
                       plain
                       size="small"
                       @click="updateStatusEdit">
              <span v-show="this.form.status == 1">停用</span>
              <span v-show="this.form.status == 0">启用</span>
            </el-button>
          </el-col>
        </el-row>
        <div style="margin-top: 20px"></div>
        <el-row>
          <el-col :span="1">
            <span>提示词</span>
          </el-col>
          <el-col :span="22">
            <div style="width: 100%;height:550px; overflow-y: auto;border: 1px solid #666666;margin-left: 15px">
              {{this.form.promptWord}}
            </div>
          </el-col>
        </el-row>
      </div>
      <!--修改-->
      <div v-show="isEdit" style="margin-left: 15px">
        <el-form :model="form" ref="form" :rules="rules">
          <el-row>
            <el-col :span="4">
              <el-form-item prop="logoUrl">
                <el-col :span="8">
                  <el-avatar shape="square" :src="form.logoUrl" :size="60"></el-avatar>
                </el-col>
                <el-col :span="16">
                  <div>
                    <el-upload
                      class="upload-template"
                      ref="upload"
                      :action="uploadUrl"
                      :limit="1"
                      :show-file-list="false"
                      :before-upload="handleBeforeUpload"
                      :on-success="handleUploadSuccess"
                      :on-error="handleUploadError"
                      :headers="headers">
                      <el-button size="small"
                                 plain>上传图片</el-button>
                      <div slot="tip" class="el-upload__tip">建议图片像素为76*76px</div>
                    </el-upload>
                  </div>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="大模型类型" prop="modelType">
                <el-col :span="13">
                  <el-select v-model="form.modelType" placeholder="请选择大模型类型" size="small">
                    <el-option
                      v-for="item in dict.type.model_type"
                      :key="parseInt(item.value)"
                      :label="item.label"
                      :value="parseInt(item.value)">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="模型名称" prop="name">
                <el-col :span="10">
                  <el-input v-model="form.name" placeholder="请输入模型名称" size="small" type="text"></el-input>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item>
                <el-col :span="24">
                  <el-button type="info" plain size="mini" @click="submitForm">保存</el-button>
                  <el-button type="primary" size="mini" @click="testModelCollection">测试联通</el-button>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="15">
              <el-form-item label="接口信息" prop="modelParam">
                <el-col :span="12">
                  <el-input v-model="form.modelParam" placeholder="接口信息" size="small" type="textarea" :cols="12" :rows="7"></el-input>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="提示词" prop="promptWord">
                <el-col :span="22">
                  <el-input v-model="form.promptWord" placeholder="提示词" size="small" type="textarea" :cols="20" :rows="24"></el-input>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listModelAppInfo, updateModelAppInfoStatus, deleteModelAppInfo, updateModelAppInfo, selectModelAppInfo, insertModelAppInfo, isModelCollection} from "@/api/platform/model/model";
import {getToken} from "@/utils/auth";
export default {
  name: "ModelConfig",
  dicts: ['model_type'],
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('人设名称不能为空'));
      }
      setTimeout(() => {
        if(value.length > 20){
          callback(new Error('名称必须20个字一下'));
        }else{
          callback();
        }
      }, 1000);
    };
    let checkModelParam = (rule, value, callback) => {
        try {
          let obj = JSON.parse(value)
          if(typeof obj == 'object' && obj){
            callback();
          }
        }catch(error){
          return callback(new Error('接口参数格式错误'));
        }
    };
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      isEdit: false,
      operationType: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      modelConfigList: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示添加修改弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { validator: checkName, trigger: "blur" },
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        modelType: [
          { required: true, message: "大模型类型不能为空", trigger: "blur" }
        ],
        modelParam: [
          { validator: checkModelParam, trigger: "blur" },
          { required: true, message: "接口参数信息不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listModelAppInfo(this.queryParams).then(response => {
        this.modelConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    copyText(){
      this.$message.success("复制成功")
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`文件格式错误!`);
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = (file.size / 1024 / 1024 < this.fileSize.default);
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.fileUid = res.data.uid;
        this.form.logoUrl = res.data.url;
        this.$message.success("上传成功");
        this.$refs.upload.clearFiles()

      } else {
        this.$message.error("上传失败");
      }
    },
    handleUploadError() {
      this.$message.error("上传失败");
    },
    //table表格格式化
    modelNameFormat(row, index) {
      let list = this.dict.type.model_type;
      const map = list.reduce((acc, item) => {
        acc[item.value] = item;
        return acc;
      }, {});
      const key = row.modelType.toString();
      let object = map[key];
      if(object != null || object != undefined){
        return object.label;
      }
      return "暂无"
    },
    handlerDeleteEdit(){
      let row = this.form;
      this.handleDelete(row)
    },
    updateStatusEdit(){
      let data = this.form;
      let message;
      if(data.status == 0){
        message = "确定要启用大模型：" + data.name + "吗？"+
          "\n大模型ID：" + data.uid

      }else{
        message = "确定要停用大模型：" + data.name + "吗？" +
          "\n大模型ID：" + data.uid
      }
      this.$modal.confirm(message).then(function() {
        return updateModelAppInfoStatus(data);
      }).then(() => {
        if (data.status == 0) {
          this.$modal.msgSuccess("已启用");
        } else {
          this.$modal.msgSuccess("已停用");
        }
        selectModelAppInfo(data.uid).then(response =>{
          this.form = response.data;
          let row = this.form;
          let modelNameValue = this.modelNameFormat(row, 0);
          this.form.modelName = modelNameValue;
        })
      }).catch(() => {});

    },
    //修改配置状态
    updateStatus(row){
      let data ={};
      let message;
      if(row.status == 0){
        message = "确定要启用大模型：" + row.name + "吗？"+
          "\n大模型ID：" + row.uid

      }else{
        message = "确定要停用大模型：" + row.name + "吗？" +
          "\n大模型ID：" + row.uid
      }
      data.uid = row.uid;
      this.$modal.confirm(message).then(function() {
        return updateModelAppInfoStatus(data);
      }).then(() => {
        if (row.status == 0) {
          this.$modal.msgSuccess("已启用");
        } else {
          this.$modal.msgSuccess("已停用");
        }
        this.getList();
      }).catch(() => {});
    },
    handleStatusChange(row){
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.open= false;
      this.isEdit = false;
    },
    handlerEdit(){
      this.isEdit = true;
      let row=this.form;
      this.handleUpdate(row);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.title = "新增模型";
      this.form.logoUrl= "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title="模型详情"
      this.open=true;
      this.isEdit = true
      this.getDetail(row)
    },
    handleDetail(row){
      this.reset();
      this.title="模型详情"
      this.open=true;
      this.isEdit = false;
      this.getDetail(row)
    },

    getDetail(row){
      selectModelAppInfo(row.uid).then(response =>{
        if(response.code == 200){
          this.form = response.data

          this.form.modelParam = JSON.stringify(JSON.parse(this.form.modelParam), null, 2);
          let row = this.form;
          let modelNameValue = this.modelNameFormat(row, 0);
          this.form.modelName = modelNameValue;
        }
      })
    },

    testModelCollection(){
      isModelCollection(this.form).then(response =>{
        if(response.code == 200){
          this.$modal.msgSuccess(response.msg);
        }
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uid == undefined) {
            insertModelAppInfo(this.form).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            })
          }else{
            let data = this.form;
            //提示
            const message = "<div>确定要修改配置信息？</div>"
            this.$modal.confirm(message).then(function() {
              data.status = null;
              return updateModelAppInfo(data);
            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let data = {}
      data.uid = row.uid;
      data.name = row.name;
      //提示
      const message = "<div>确定要删除应用: <span>" + data.name + " ?</span></div>"+
        "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + data.uid
      this.$modal.confirm(message).then(function() {
        return deleteModelAppInfo(data);
      }).then(() => {
        this.isEdit = false;
        this.open= false
        this.$modal.msgSuccess("删除成功");
        this.getList()
      })
    },
  }
};
</script>
<style scoped>
/deep/ .el-textarea__inner {
  resize: none;
}
</style>
